from django.http import HttpResponse, JsonResponse
import json
import datetime
import time
from django.core import serializers
# Create your views here.
from index.Anchor import Anchor
from index.models import Data
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger, InvalidPage


def index(request):
    result = {
        "code": 200,
        "msg": "error",
        "data": ""
    }
    return HttpResponse(json.dumps(result))


def up_data(request):
    try:
        if request.method == "GET":
            error_msg = request.session.get('error_message')
            data = {
                "code": 0,
                "msg": "失败",
                "data": "",
            }
            result = {
                "code": 200,
                "msg": error_msg,
                "data": data
            }
            return HttpResponse(json.dumps(result))

        elif request.method == "POST":
            open_id = request.POST.get("open_id")
            n1 = request.POST.get("N1")
            n2 = request.POST.get("N2")
            lembed = request.POST.get("Lembed")
            lbond = request.POST.get("Lbond")
            ahole = request.POST.get("Ahole")
            n = request.POST.get("n")
            ea = request.POST.get("EA")
            v = request.POST.get("v")
            pg1 = request.POST.get("Pg1")
            pg2 = request.POST.get("Pg2")
            p = request.POST.get("P")

            anchor_data = {
                "N1": n1,
                "N2": n2,
                "Lembed": lembed,
                "Lbond": lbond,
                "Ahole": ahole,
                "n": n,
                "EA": ea,
                "V": v,
                "Pg1": pg1,
                "Pg2": pg2,
                "P": p,
            }

            anchor = Anchor()
            result_data = anchor.anchor_data(open_id, anchor_data)
            en_file_name = result_data[0]
            ch_file_name = result_data[1]
            y_predict = result_data[2]

            data = Data()
            data.open_id = open_id
            data.data_n1 = n1
            data.data_n2 = n2
            data.data_lembed = lembed
            data.data_lbond = lbond
            data.data_ahole = ahole
            data.data_n = n
            data.data_ea = ea
            data.data_v = v
            data.data_pg1 = pg1
            data.data_pg2 = pg2
            data.data_pmax = p
            data.en_file_name = en_file_name
            data.ch_file_name = ch_file_name

            predict = ""
            for i in range(len(y_predict)):
                print(y_predict[i])
                ll = len(y_predict) - 1
                if i == ll:
                    if y_predict[i] < 0:
                        y_predict[i] = 0
                    predict = predict + str(y_predict[i])
                else:
                    if y_predict[i] < 0:
                        y_predict[i] = 0
                    predict = predict + str(y_predict[i]) + ","
            """
            for x in y_predict:
                print(x)
                ll = len(y_predict)
                if y_predict == ll:
                    predict = predict + str(x)
                else:
                    predict = predict + str(x) + ","
            """

            data.y_predict = predict
            data.is_more = 0
            data.status = 1
            data.create_id = open_id

            data.save()

            result_d = {
                "en_file": en_file_name,
                "ch_file": ch_file_name,
                "y_predict": predict,
            }
            data = {
                "code": 1,
                "msg": "计算成功！",
                "data": result_d,
            }
            result = {
                "code": 200,
                "msg": "ok",
                "data": data
            }
            return HttpResponse(json.dumps(result, default=DateEncoder))
    except Exception as ret:
        print(ret)
        data = {
            "code": 0,
            "msg": "计算失败！",
            "data": "",
        }
        result = {
            "code": 200,
            "msg": "error",
            "data": data
        }
        return HttpResponse(json.dumps(result))
    else:
        data = {
            "code": 0,
            "msg": "计算失败！",
            "data": "",
        }
        result = {
            "code": 200,
            "msg": "error",
            "data": data
        }
        return HttpResponse(json.dumps(result))


def example_data(request):
    try:
        if request.method == "GET":
            error_msg = request.session.get('error_message')
            data = {
                "code": 0,
                "msg": "失败",
                "data": "",
            }
            result = {
                "code": 200,
                "msg": error_msg,
                "data": data
            }
            return HttpResponse(json.dumps(result))

        elif request.method == "POST":
            open_id = "example"
            example = Data.objects.filter(open_id=open_id)
            if example.exists():
                example_d = example.first()
                result_d = {
                    "en_file": example_d.en_file_name,
                    "ch_file": example_d.ch_file_name,
                    "y_predict": example_d.y_predict,
                    "N1": example_d.data_n1,
                    "N2": example_d.data_n2,
                    "Lembed": example_d.data_lembed,
                    "Lbond": example_d.data_lbond,
                    "Ahole": example_d.data_ahole,
                    "n": example_d.data_n,
                    "EA": example_d.data_ea,
                    "V": example_d.data_v,
                    "Pg1": example_d.data_pg1,
                    "Pg2": example_d.data_pg2,
                    "P": example_d.data_pmax,
                }
                data = {
                    "code": 1,
                    "msg": "成功！",
                    "data": result_d,
                }
                result = {
                    "code": 200,
                    "msg": "ok",
                    "data": data
                }
                return HttpResponse(json.dumps(result, default=DateEncoder))
            else:
                data = {
                    "code": 0,
                    "msg": "请求失败！",
                    "data": "",
                }
                result = {
                    "code": 200,
                    "msg": "error",
                    "data": data
                }
                return HttpResponse(json.dumps(result))
    except Exception as ret:
        print(ret)
        data = {
            "code": 0,
            "msg": "请求失败！",
            "data": "",
        }
        result = {
            "code": 200,
            "msg": "error",
            "data": data
        }
        return HttpResponse(json.dumps(result))
    else:
        data = {
            "code": 0,
            "msg": "请求失败！",
            "data": "",
        }
        result = {
            "code": 200,
            "msg": "error",
            "data": data
        }
        return HttpResponse(json.dumps(result))


def my_list(request):
    if request.method == "GET":
        error_msg = request.session.get('error_message')
        data = {
            "code": 0,
            "msg": "失败",
            "data": "",
        }
        result = {
            "code": 200,
            "msg": error_msg,
            "data": data
        }
        return HttpResponse(json.dumps(result))
    elif request.method == "POST":
        open_id = request.POST.get("open_id")

        page = int(request.POST.get('page_mun'))
        pageSize = int(request.POST.get('page_size'))
        data_list = Data.objects.all().filter(open_id=open_id).order_by("create_time")
        paginator = Paginator(data_list, pageSize)
        total_n = paginator.count
        try:
            paginator = paginator.page(page)
        except PageNotAnInteger:
            paginator = paginator.page(1)
        except EmptyPage:
            paginator = paginator.page(paginator.num_pages)

        json_data = serializers.serialize("json", paginator, ensure_ascii=False)
        result_d = {
            "page": page,
            "pageSize": pageSize,
            "total": total_n,
            "list": json_data,
        }
        data = {
            "code": 1,
            "msg": "成功！",
            "data": result_d,
        }
        result = {
            "code": 200,
            "msg": "ok",
            "data": data
        }
        return HttpResponse(json.dumps(result, default=DateEncoder))


def DateEncoder(obj):
    if isinstance(obj, (datetime.datetime, datetime.date)):
        return obj.strftime('%Y-%m-%d')
